package com.kitten.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@Slf4j
public class AuthenticationController {
      RequestCache requestCache = new HttpSessionRequestCache();

      RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

      @RequestMapping("/authentication/require")
      public  String require(HttpServletRequest request, HttpServletResponse response) throws IOException {
            SavedRequest savedRequest = requestCache.getRequest(request, response);

            if (savedRequest != null) {
                  String targetUrl = savedRequest.getRedirectUrl();
                  log.info("引发跳转的请求是:" + targetUrl);
                  if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
                        redirectStrategy.sendRedirect(request, response, "signIn.html");
                  }
            }
            return  "访问的服务需要身份认证，请引导用户到登录页";
      }


      /**
       * 用户信息校验
       * @param authentication 信息
       * @return 用户信息
       */
      @RequestMapping("/user/me")
      public Object user(Authentication authentication) {
            return authentication.getPrincipal();
      }

}
